package com.douqu.game.main.msg;

import com.douqu.game.core.config.PlayerLvConfig;
import com.douqu.game.core.config.ResolveConfig;
import com.douqu.game.core.config.StableDataConfig;
import com.douqu.game.core.config.card.CardLvConfig;
import com.douqu.game.core.config.card.CardStarConfig;
import com.douqu.game.core.config.common.GoodsData;
import com.douqu.game.core.config.drop.DropGroupConfig;
import com.douqu.game.core.config.goods.AccessoryIntensifyConfig;
import com.douqu.game.core.config.goods.AccessoryUpConfig;
import com.douqu.game.core.config.goods.EquipIntensifyConfig;
import com.douqu.game.core.config.goods.PropConfig;
import com.douqu.game.core.controller.PlayerController;
import com.douqu.game.core.e.E_StableDataType;
import com.douqu.game.core.entity.db.AccessoryDB;
import com.douqu.game.core.entity.db.CardDB;
import com.douqu.game.core.entity.db.EquipDB;
import com.douqu.game.core.entity.db.PropDB;
import com.douqu.game.core.entity.ext.BagInfo;
import com.douqu.game.core.entity.ext.SettingInfo;
import com.douqu.game.core.entity.ext.TaskInfo;
import com.douqu.game.core.entity.ext.data.card.CardData;
import com.douqu.game.core.entity.ext.data.challenge.HegemonyScoreChangeBean;
import com.douqu.game.core.factory.ConstantFactory;
import com.douqu.game.core.factory.DataFactory;
import com.douqu.game.core.factory.TaskFactory;
import com.douqu.game.core.factory.WordFactory;
import com.douqu.game.core.protobuf.SGBagProto;
import com.douqu.game.core.protobuf.SGCommonProto;
import com.douqu.game.core.protobuf.SGMainProto;
import com.douqu.game.core.util.LogUtils;
import com.douqu.game.core.util.SendUtils;
import com.douqu.game.main.GameServer;
import com.google.protobuf.InvalidProtocolBufferException;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by bean on 2017/7/21.
 */
@Component
public class BagMsgChannel implements AMsgChannel {

	@Override
	public void messageChannel(int code, PlayerController playerController, byte[] data) throws Exception {
		if (playerController == null)
			throw new Exception("playerController is null");

		int beforeFC = playerController.getPlayer().fc;

		switch (code) {
		// 兵种升级
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardLevelUp_VALUE:
			SGBagProto.C2S_CardLevelUp c = SGBagProto.C2S_CardLevelUp.parseFrom(data);
			// bagInfo.cardLV(playerController, c == null ? 0 : c.getSid());
			break;
		// 我的卡包
		// case SGMainProto.E_MSG_ID.MsgID_Bag_MyCard_VALUE:
		// playerController.getPlayerResult().getCardData().myCardList(playerController);
		// break;
		// 卡组列表
		case SGMainProto.E_MSG_ID.MsgID_Bag_MyCardTeam_VALUE:
			playerController.getPlayer().getCardData().myCardTeam(playerController);
			break;
		// 设置出阵列表
		// case SGMainProto.E_MSG_ID.MsgID_Bag_SetBattleCardTeam_VALUE:
		// SGBagProto.C2S_SetBattleCardTeam cardTeam =
		// SGBagProto.C2S_SetBattleCardTeam.parseFrom(data);
		// playerController.getPlayerResult().getCardData().setBattleCardTeam(playerController,
		// cardTeam.getCardTeamId());
		// break;
		// 替换卡片
		case SGMainProto.E_MSG_ID.MsgID_Bag_SetCardReplace_VALUE:
			SGBagProto.C2S_CardReplace replace = SGBagProto.C2S_CardReplace.parseFrom(data);
			playerController.getPlayer().getCardData().cardReplace(playerController, replace.getCardGroupId(),
					replace.getActiveCardId(), replace.getPassiveCardId());
			break;
		// 替换卡片
		case SGMainProto.E_MSG_ID.MsgID_Bag_QuitBattleGroup_VALUE:
			SGBagProto.C2S_QuitBattleGroup quitBattleGroup = SGBagProto.C2S_QuitBattleGroup.parseFrom(data);
			playerController.getPlayer().getCardData().quitBattle(playerController, quitBattleGroup.getCardGroupId(),
					quitBattleGroup.getActiveCardId());
			break;
		// 卡牌详情 508
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardDetail_VALUE:
			SGBagProto.C2S_CardDetail cardDetail = SGBagProto.C2S_CardDetail.parseFrom(data);
			playerController.getPlayer().getCardData().cardDetail(playerController, cardDetail.getCardId());
			break;
		// 卡牌升级 509
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardUpLv_VALUE:
			SGBagProto.C2S_CardUpLv cardUpLv = SGBagProto.C2S_CardUpLv.parseFrom(data);
			playerController.getPlayer().getCardData().cardLv(playerController, cardUpLv.getCardId(),
					cardUpLv.getNeedLv());
			break;
		// 卡牌升星 510
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardUpStar_VALUE:
			SGBagProto.C2S_CardUpStar cardUpStar = SGBagProto.C2S_CardUpStar.parseFrom(data);
			playerController.getPlayer().getCardData().cardStar(playerController, cardUpStar.getCardId());
			break;
		// 激活宿命 511
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardFate_VALUE:
			SGBagProto.C2S_CardFate cardFate = SGBagProto.C2S_CardFate.parseFrom(data);
			playerController.getPlayer().getCardData().cardFate(playerController, cardFate.getCardId(),
					cardFate.getFateId());
			break;
		// 宿命列表 512
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardFateList_VALUE:
			SGBagProto.C2S_CardFateList cardFateList = SGBagProto.C2S_CardFateList.parseFrom(data);
			playerController.getPlayer().getCardData().cardFateList(playerController, cardFateList.getCardId());
			break;
		// 装备强化
		case SGMainProto.E_MSG_ID.MsgID_Bag_EquipIntensify_VALUE:
			SGBagProto.C2S_EquipIntensify equipIntensify = SGBagProto.C2S_EquipIntensify.parseFrom(data);
			playerController.getPlayer().getCardData().equipIntensify(playerController, equipIntensify.getCardId(),
					equipIntensify.getEquipTypeValue(), equipIntensify.getCount());
			break;
		// 装备合成
		case SGMainProto.E_MSG_ID.MsgID_Bag_EquipUp_VALUE:
			SGBagProto.C2S_EquipUp equipUp = SGBagProto.C2S_EquipUp.parseFrom(data);
			playerController.getPlayer().getCardData().equipSyn(playerController, equipUp.getCardId(),
					equipUp.getEquipTypeValue());
			break;
		// 饰品进阶 515
		case SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryUp_VALUE:
			SGBagProto.C2S_AccessoryUp accessoryUp = SGBagProto.C2S_AccessoryUp.parseFrom(data);
			playerController.getPlayer().getCardData().accessoryUp(playerController, accessoryUp.getCardId(),
					accessoryUp.getAccessoryTypeValue());
			break;

		// 饰品强化 516
		case SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryIntensify_VALUE:
			SGBagProto.C2S_AccessoryIntensify accessoryIntensify = SGBagProto.C2S_AccessoryIntensify.parseFrom(data);
			playerController.getPlayer().getCardData().accessoryIntensify(playerController,
					accessoryIntensify.getCardId(), accessoryIntensify.getAccessoryTypeValue());
			break;

		// 卡牌升级添加经验卷轴 517
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardAddExp_VALUE:
			SGBagProto.C2S_CardAddExp cardAddExp = SGBagProto.C2S_CardAddExp.parseFrom(data);
			playerController.getPlayer().getCardData().cardExp(playerController, cardAddExp.getCardId(),
					cardAddExp.getExpId(), cardAddExp.getCount());
			break;
		// 饰品强化经验卷轴升级 518
		case SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryAddExp_VALUE:
			SGBagProto.C2S_AccessoryAddExp accessoryAddExp = SGBagProto.C2S_AccessoryAddExp.parseFrom(data);
			playerController.getPlayer().getCardData().accessoryAddExp(playerController, accessoryAddExp.getCardId(),
					accessoryAddExp.getExpId(), accessoryAddExp.getCount(), accessoryAddExp.getAccessoryTypeValue());
			break;
		// 卡牌合成 519
		case SGMainProto.E_MSG_ID.MsgID_Bag_CardSyn_VALUE:
			SGBagProto.C2S_CardSyn cardSyn = SGBagProto.C2S_CardSyn.parseFrom(data);
			playerController.getPlayer().getCardData().cardSyn(playerController, cardSyn.getSynId());
			break;
		// 饰品激活 526
		case SGMainProto.E_MSG_ID.MsgID_Bag_AccessoryActivated_VALUE:
			SGBagProto.C2S_AccessoryActivated aac = SGBagProto.C2S_AccessoryActivated.parseFrom(data);
			playerController.getPlayer().getCardData().accessoryActivated(playerController, aac.getCardId(),
					aac.getAccessoryTypeValue());
			break;
		// 上阵卡片替换 527
		case SGMainProto.E_MSG_ID.MsgID_Bag_BattleCardReset_VALUE:
			battleCardReset(playerController, data, code);
			break;
		// 一键强化 528
		case SGMainProto.E_MSG_ID.MsgID_Bag_EquipIntensifyOneKey_VALUE:
			SGBagProto.C2S_EquipIntensifyOneKey equipIntensifyOneKey = SGBagProto.C2S_EquipIntensifyOneKey
					.parseFrom(data);
			playerController.getPlayer().getCardData().equipIntensifyOneKey(playerController,
					equipIntensifyOneKey.getCardId());
			break;

		/******************************* 重生阁 *************************************/
		// 520卡牌重生
		case SGMainProto.E_MSG_ID.MsgID_Bag_RebirthCard_VALUE:
			rebirthCard(playerController, data, code);
			break;
		// 521 英魂分解可分解卡牌预览
		case SGMainProto.E_MSG_ID.MsgID_Bag_ResolveCardPreview_VALUE:
			resolveCardPreview(playerController, data, code);
			break;
		// 522 英魂分解
		case SGMainProto.E_MSG_ID.MsgID_Bag_SoulResolve_VALUE:
			soulResolve(playerController, data, code);
			break;
		// 523 装备碎片分解
		case SGMainProto.E_MSG_ID.MsgID_Bag_EquipResolve_VALUE:
			equipResolve(playerController, data, code);
			break;
        // 529 快捷上阵
        case SGMainProto.E_MSG_ID.MsgID_Player_FastToBattle_VALUE:
            SGBagProto.C2S_FastToBattle cards = SGBagProto.C2S_FastToBattle.parseFrom(data);
            playerController.getPlayer().getCardData().cardReplaceByOneKey(playerController, cards.getUpList(),cards.getDownList());
            break;
		/***************************** 使用道具 ******************************/
		case SGMainProto.E_MSG_ID.MsgID_Bag_UseProp_VALUE:
			useProp(playerController, code, data);
			break;
		default:
			break;
		}

		int afterFC = playerController.getPlayer().fc;

		if (beforeFC != afterFC) {
			GameServer.getInstance().getWorldManager().updateRankInfo(SGCommonProto.E_RANK_TYPE.RANK_TYPE_FC,
					playerController.getPlayer(), afterFC);
		}
	}

	/**
	 * 上阵卡片替换
	 *
	 * @param playerController
	 * @param data
	 * @param code
	 */
	private void battleCardReset(PlayerController playerController, byte[] data, int code) {
		SGBagProto.C2S_BattleCardReset request = null;
		try {
			request = SGBagProto.C2S_BattleCardReset.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (request == null) {
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}

		List<Integer> battleCardIds = request.getCardIdList();
		LogUtils.debug("上阵卡组替换请求参数：" + battleCardIds);
		CardData cardData = playerController.getPlayer().getCardData();
		for (Integer id : battleCardIds) {
			if (DataFactory.getInstance().getGameObject(DataFactory.CARD_KEY, id) == null
					&& cardData.getCard(id) == null) {
				playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
				return;
			}
		}

		List<CardDB> localBattleCardList = cardData.getBattleCardList();
		// 先将所有的卡片全部下阵
		for (CardDB cardDB : localBattleCardList) {
			cardData.changeCardBattleStatus(cardDB, false);
		}

		// 再将需要的卡牌设置上阵
		for (Integer id : battleCardIds) {
			CardDB card = cardData.getCard(id);
			cardData.changeCardBattleStatus(card, true);
		}

		PlayerLvConfig playerLvConfig = DataFactory.getInstance().getGameObject(DataFactory.PLAYER_LV_KEY,
				playerController.getPlayer().getLv());
		int offsetCardCount = playerLvConfig.minBattleSoldierCount - cardData.getBattleCardList().size();
		if (offsetCardCount > 0) {
			// 需要自动加入offsetCardCount张卡到上阵卡组
			List<CardDB> sleepCardList = cardData.getSleepCardList();
			sleepCardList.sort(new Comparator<CardDB>() {
				@Override
				public int compare(CardDB o1, CardDB o2) {
					return new Integer(o2.fc).compareTo(o1.fc);
				}
			});
			int getCount = Math.max(sleepCardList.size(), offsetCardCount);
			List<CardDB> cardDBs = sleepCardList.subList(0, getCount);
			for (CardDB cardDB : cardDBs) {
				cardData.changeCardBattleStatus(cardDB, true);
			}
		}

		// 将最终的卡组发给前端
		SGBagProto.S2C_BattleCardReset.Builder response = SGBagProto.S2C_BattleCardReset.newBuilder();
		SGCommonProto.CardGroup.Builder cardGroup = null;
		SGCommonProto.Card.Builder cardInfo = null;
		SGCommonProto.Accessory.Builder accessory = null;
		SGCommonProto.Equip.Builder equip = null;
		int groupId = 0;
		cardGroup = SGCommonProto.CardGroup.newBuilder();
		cardGroup.setGroupId(++groupId);
		cardGroup.setCardGroupType(SGCommonProto.E_CARDGROUP_TYPE.CARDGROUP_TYPE_BATTLE);
		for (CardDB cardDB : cardData.getBattleCardList()) {
			cardInfo = SGCommonProto.Card.newBuilder();
			cardInfo.setId(cardDB.id);
			cardInfo.setLv(cardDB.getLv());
			cardInfo.setStar(cardDB.star);
			cardInfo.setCurExp(cardDB.getExp());
			cardInfo.setFc(cardDB.fc);
			// 饰品
			for (Map.Entry<Integer, AccessoryDB> entry : cardDB.getAccessoryMap().entrySet()) {
				accessory = SGCommonProto.Accessory.newBuilder();
				accessory.setId(entry.getValue().id);
				accessory.setIntensifyLv(entry.getValue().getLv());
				accessory.setCurrentExp(entry.getValue().getExp());
				accessory.setIsActivated(entry.getValue().isActivated);
				accessory.setUpLv(entry.getValue().upLv);
				cardInfo.addAccessory(accessory);
			}
			// 装备
			for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
				equip = SGCommonProto.Equip.newBuilder();
				equip.setId(entry.getValue().id);
				equip.setLv(entry.getValue().getLv());
				cardInfo.addEquip(equip);
			}
			// 宿命列表
			cardInfo.addAllActiveFateList(cardDB.getActiveFateList());
			// 吃药
			cardInfo.addAllUseLiquidCount(cardDB.getUseLiquidProp());
			cardGroup.addCards(cardInfo);
		}

		response.addCardGroups(cardGroup);

		cardGroup = SGCommonProto.CardGroup.newBuilder();
		cardGroup.setGroupId(++groupId);
		cardGroup.setCardGroupType(SGCommonProto.E_CARDGROUP_TYPE.CARDGROUP_TYPE_SLEEP);
		for (CardDB cardDB : cardData.getSleepCardList()) {
			cardInfo = SGCommonProto.Card.newBuilder();
			cardInfo.setId(cardDB.id);
			cardInfo.setLv(cardDB.getLv());
			cardInfo.setStar(cardDB.star);
			cardInfo.setCurExp(cardDB.getExp());
			cardInfo.setFc(cardDB.fc);

			// 饰品
			for (Map.Entry<Integer, AccessoryDB> entry : cardDB.getAccessoryMap().entrySet()) {
				accessory = SGCommonProto.Accessory.newBuilder();
				accessory.setId(entry.getValue().id);
				accessory.setIntensifyLv(entry.getValue().getLv());
				accessory.setCurrentExp(entry.getValue().getExp());
				accessory.setIsActivated(entry.getValue().isActivated);
				accessory.setUpLv(entry.getValue().upLv);
				cardInfo.addAccessory(accessory);
			}
			// 装备
			for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
				equip = SGCommonProto.Equip.newBuilder();
				equip.setId(entry.getValue().id);
				equip.setLv(entry.getValue().getLv());
				cardInfo.addEquip(equip);
			}
			// 宿命列表
			cardInfo.addAllActiveFateList(cardDB.getActiveFateList());
			cardGroup.addCards(cardInfo);
		}
		response.addCardGroups(cardGroup);

		playerController.sendMsg(code, response.build().toByteArray());

	}

	/**
	 * 道具的使用
	 *
	 * @param playerController
	 * @param code
	 * @param data
	 */
	private void useProp(PlayerController playerController, int code, byte[] data) {
		SGBagProto.C2S_UseProp request = null;
		try {
			request = SGBagProto.C2S_UseProp.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (request == null) {
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}

		int propId = request.getPropId();
		int useCount = request.getCount();
		LogUtils.debug("道具使用参数:" + request.toString());
		PropConfig propConfig = DataFactory.getInstance().getGameObject(DataFactory.PROP_KEY, propId);
		if (useCount <= 0 || propConfig == null || (propConfig.type != ConstantFactory.PROP_TYPE_BAG
				&& propConfig.type != ConstantFactory.PROP_TYPE_CAMP_BOX
				&& propConfig.type != ConstantFactory.PROP_TYPE_MORE_MILITARY
				&& propConfig.type != ConstantFactory.PROP_TYPE_MILITARY_CAPITAL)) {
//			LogUtils.error("找不到道具，或者数量错误,或者物品不可使用");
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}

		if (useCount > 100) {
//			LogUtils.info("物品使用次数超出系统限制");
			playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, propId);
			return;
		}

		BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
		if (bagInfo.getPropCount(propId) < useCount) {
//			LogUtils.info("物品数量不足");
			playerController.sendWarn(WordFactory.GOODS_NOT_ENOUGH, propId);
			return;
		}

		int droupConfigId = propConfig.effectValue;
		// 阵营宝箱 特殊处理
		if (propConfig.type == ConstantFactory.PROP_TYPE_CAMP_BOX) {
			droupConfigId = propConfig.campDropGroup[playerController.getPlayer().camp - 1];
		}
		// 军资类型
		if (propConfig.type == ConstantFactory.PROP_TYPE_MORE_MILITARY) {
			HegemonyScoreChangeBean changeBean = playerController.getPlayer().getWorldMapKillData().useMilitary(propConfig, useCount);
			SendUtils.sendHegemoneyChange(playerController, changeBean);
		}
		else if (propConfig.type == ConstantFactory.PROP_TYPE_MILITARY_CAPITAL)
		{
			//使用军资类道具
			playerController.getPlayer().getExtInfo(SettingInfo.class).getAutoRecover().setMilitaryPropId(propConfig.id);
			playerController.sendWarn(WordFactory.USE_PROP_MILITARY,propConfig.effectValue);
		}
		else{
			DropGroupConfig dropGroupConfig = DataFactory.getInstance().getGameObject(DataFactory.DROP_GROUP_KEY,
					droupConfigId);
			dropGroupConfig.reward(playerController, useCount);
		}

		// 扣除使用的道具
		bagInfo.addProp(propId, -useCount);

		SGBagProto.S2C_UseProp.Builder response = SGBagProto.S2C_UseProp.newBuilder();
		response.setPropId(propId);
		response.setCount(useCount);
		playerController.sendMsg(code, response.build().toByteArray());
	}

	/**
	 * 卡片重生
	 *
	 * @param playerController
	 * @param data
	 * @param code
	 */
	private void rebirthCard(PlayerController playerController, byte[] data, int code) {
		SGBagProto.C2S_RebirthCard request = null;
		try {
			request = SGBagProto.C2S_RebirthCard.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (request == null) {
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}
		int cardId = request.getCardId();
		LogUtils.debug("卡片重生返回参数:" + cardId);
		BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
		StableDataConfig stableDataConfig = DataFactory.getInstance().getGameObject(DataFactory.STABLE_DATA_KEY,
				E_StableDataType.REBIRTH_CARD_CONSUME.getCode());
		if (bagInfo.getAsset(stableDataConfig.goods[0].id) < stableDataConfig.goods[0].value) {
			// 钻石资源不足
			LogUtils.debug("钻石资源不足" + stableDataConfig.goods[0].value);
			playerController.sendWarn(WordFactory.ASSET_NOT_ENOUGH, stableDataConfig.goods[0].id);
			return;
		}

		CardDB cardDB = bagInfo.getCardData().getCard(cardId);
		if (cardDB == null) {
			// 卡片不存在
			LogUtils.error("卡片不存在" + cardId);
			playerController.sendWarn(WordFactory.CARD_NOTHING_ERROR);
			return;
		}
		// 上阵卡组
		// List<Integer> cardList =
		// bagInfo.getCardData().getCardTeamMap().get(bagInfo.getCardData().getBattleCardIndex());
		List<CardDB> cardList = bagInfo.getCardData().getBattleCardList();
		if (cardDB.battle) {
			// 上阵卡组的卡片不能重生
			LogUtils.error("上阵卡组的卡片不能重生" + cardId);
			playerController.sendWarn(WordFactory.BATTLE_CARD_NOT_REBIRTH);
			return;
		}

		if (!cardDB.hasTrain()) {
			// 卡片还未培养
			LogUtils.debug("卡片还未培养" + cardId);
			playerController.sendWarn(WordFactory.CARD_NOT_TRAIN);
			return;
		}

		List<GoodsData> tempRestitutionList = new ArrayList<>();
		int cardQuality = cardDB.getConfig().quality;
		// 卡片升级返回
		if (cardDB.getLv() > 1) {
			CardLvConfig cardLvConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_LV_KEY,
					cardDB.getLv());
			if (cardLvConfig != null) {
				for (GoodsData goodsData : cardLvConfig.restitution) {
					if (goodsData.type == cardQuality) {
						addGoodsToList(tempRestitutionList, new GoodsData(
								SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, goodsData.id, goodsData.value));
					}
				}
			}
			// bagInfo.addGoods(cardLvConfig.restitution, null);

		}

		// 卡片升星
		CardStarConfig cardStarConfig = DataFactory.getInstance().getGameObject(DataFactory.CARD_STAR_KEY, cardDB.star);
		if (cardStarConfig != null) {
			for (GoodsData goodsData : cardStarConfig.restitutionItem) {
				if (goodsData.type == cardQuality) {
					addGoodsToList(tempRestitutionList, new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE,
							goodsData.id, goodsData.value));
				}
			}

			for (GoodsData goodsData : cardStarConfig.restitutionResource) {
				if (goodsData.type == cardQuality) {
					addGoodsToList(tempRestitutionList, new GoodsData(
							SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE, goodsData.id, goodsData.value));
				}
			}
			// bagInfo.addGoods(cardStarConfig.restitution, null);
			// 返回碎片
			// bagInfo.addGoods(new GoodsData[]{new
			// GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, cardId,
			// cardStarConfig.backDebris)}, null);
			for (GoodsData goodsData : cardStarConfig.backDebris) {
				if (goodsData.type == cardQuality) {
					addGoodsToList(tempRestitutionList,
							new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, cardId, goodsData.value));
					break;
				}
			}
			// addGoodsToList(tempRestitutionList, new
			// GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, cardId,
			// cardStarConfig.backDebris));
			// bagInfo.addGoods(new GoodsData[]{new
			// GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, cardId,
			// cardStarConfig.backDebris)}, null);
		}

		// 装备升级和升阶
		int key;
		EquipIntensifyConfig equipIntensifyConfig;
		for (Map.Entry<Integer, EquipDB> entry : cardDB.getEquipMap().entrySet()) {
			// 装备升级
			equipIntensifyConfig = DataFactory.getInstance().getGameObject(DataFactory.EQUIP_INTENSIFY_KEY,
					entry.getValue().getLv());
			if (equipIntensifyConfig != null) {
				for (GoodsData goodData : equipIntensifyConfig.restitution) {
					if (entry.getKey() == goodData.type) {
						addGoodsToList(tempRestitutionList, new GoodsData(
								SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_ASSETS_VALUE, goodData.id, goodData.value));
						break;
					}
				}
			}
			for (GoodsData goodsData : entry.getValue().getConfig().restitution) {
				addGoodsToList(tempRestitutionList, goodsData.copy());
			}
		}

		// 饰品升级和升阶
		AccessoryIntensifyConfig accessoryIntensifyConfig;
		for (AccessoryDB accessoryDB : cardDB.getAccessoryMap().values()) {
			if (accessoryDB.isActivated) {
				// 饰品强化
				accessoryIntensifyConfig = DataFactory.getInstance().getGameObject(DataFactory.ACCESSORY_INTENSIFY_KEY,
						accessoryDB.getLv());
				if (accessoryIntensifyConfig != null) {
					for (GoodsData goodsData : accessoryIntensifyConfig.restitution) {
						if (goodsData.type == cardQuality) {
							addGoodsToList(tempRestitutionList, new GoodsData(
									SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, goodsData.id, goodsData.value));
						}
					}
				}

				// 饰品升阶
				AccessoryUpConfig accessoryUpConfig = DataFactory.getInstance()
						.getGameObject(DataFactory.ACCESSORY_UP_KEY, accessoryDB.upLv);
				if (accessoryUpConfig != null) {
					for (GoodsData goodsData : accessoryUpConfig.restitution) {
						if (goodsData.type == cardQuality) {
							addGoodsToList(tempRestitutionList, new GoodsData(
									SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, goodsData.id, goodsData.value));
						}
					}
				}
				// 激活返回
				addGoodsToList(tempRestitutionList, accessoryDB.getConfig().activate[0].copy());
			}
		}

		// 吃药的重生返回
		for (Map.Entry<Integer, Integer> entry : cardDB.getCardLiquidMap().entrySet()) {
			addGoodsToList(tempRestitutionList,
					new GoodsData(SGCommonProto.E_GOODS_TYPE.GOODS_TYPE_PROPS_VALUE, entry.getKey(), entry.getValue()));
		}

		int tempSize = tempRestitutionList.size();
		GoodsData[] goodsDatas = new GoodsData[tempSize];
		for (int i = 0; i < tempSize; i++) {
			goodsDatas[i] = tempRestitutionList.get(i);
		}

		bagInfo.addGoods(goodsDatas, null);
		LogUtils.debug("分解给后数据：" + tempRestitutionList.toString());

		// 卡牌重置
		cardDB.reset();
		// 资源扣除
		bagInfo.addGoods(new GoodsData[] {}, stableDataConfig.goods);
		// 检测任务是否完成
		playerController.getPlayer().getExtInfo(TaskInfo.class).check(TaskFactory.TASK_TARAGET_REBORN, 1);

		// 返回数据给客户端
		SGBagProto.S2C_RebirthCard.Builder response = SGBagProto.S2C_RebirthCard.newBuilder();
		response.setCardId(cardId);
		response.setCardLv(cardDB.getLv());
		response.setCardStar(cardDB.star);
		playerController.sendMsg(code, response.build().toByteArray());
	}

	public void addGoodsToList(List<GoodsData> datas, GoodsData goodsData) {
		int index = datas.indexOf(goodsData);
		if (index < 0) {
			datas.add(goodsData.copy());//必须新创建对象
		} else {
			datas.get(index).value += goodsData.value;
		}
	}

	/**
	 * 英魂分解可分解卡牌预览
	 *
	 * @param playerController
	 * @param data
	 * @param code
	 */
	private void resolveCardPreview(PlayerController playerController, byte[] data, int code) {
		BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);

		List<CardDB> cardList = bagInfo.getCardData().getSleepCardList();

		SGBagProto.S2C_ResolveCardPreview.Builder response = SGBagProto.S2C_ResolveCardPreview.newBuilder();

		for (CardDB cardDB : cardList) {
			if (cardDB.hasTrain()) { // 已经培养的剔除
				continue;
			}

			SGCommonProto.ResolveCardInfo.Builder info = SGCommonProto.ResolveCardInfo.newBuilder();
			info.setCardId(cardDB.id);
			info.setCardLevel(cardDB.getLv());
			info.setIsFate(bagInfo.hasFateLabel(cardDB.id));
			response.addInfo(info);
		}
		playerController.sendMsg(code, response.build().toByteArray());
	}

	/**
	 * 英魂分解
	 *
	 * @param playerController
	 * @param data
	 * @param code
	 */
	private void soulResolve(PlayerController playerController, byte[] data, int code) {
		SGBagProto.C2S_SoulResolve request = null;
		try {
			request = SGBagProto.C2S_SoulResolve.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (request == null) {
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}
		BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
		Map<String, GoodsData> cacheMap = new HashMap<>();
		// 碎片分解
		List<Integer> debrisIds = request.getDebrisIdsList();
		PropDB prop;
		for (Integer debrisId : debrisIds) {
			prop = bagInfo.getPropById(debrisId);
			if (prop != null && prop.getConfig().type == ConstantFactory.PROP_TYPE_CARD_SYN) {
				GoodsData[] resolveData = getResolveData(ConstantFactory.RESOLVE_TYPE_FRAGMENT,
						prop.getConfig().quality);
				if (resolveData != null) {
					// 将配置数量装换为实际数量
					GoodsData[] result = new GoodsData[resolveData.length];
					for (int i = 0; i < resolveData.length; i++) {
						result[i] = new GoodsData(resolveData[i].type, resolveData[i].id,
								resolveData[i].value * prop.count);
					}
					// bagInfo.addGoods(result, null);
					GoodsData goodsData;
					for (GoodsData g : result) {
						goodsData = cacheMap.get(g.type + "_" + g.id);
						if (goodsData == null) {
							goodsData = new GoodsData(g.type, g.id, g.value);
							cacheMap.put(g.type + "_" + g.id, goodsData);
						} else {
							goodsData.value += g.value;
						}
					}
					bagInfo.addProp(debrisId, -prop.count);
				}
			} else {
				LogUtils.error("卡片碎片分解错误，背包物品找不到或者物品不是卡片碎片：" + debrisId);
				playerController.sendWarn(WordFactory.PARAM_ERROR);
				return;
			}
		}

		GoodsData[] result = new GoodsData[cacheMap.size()];
		int i = 0;
		for (GoodsData goodsData : cacheMap.values()) {
			result[i++] = goodsData;
		}
		bagInfo.addGoods(result);

		playerController.sendMsg(code, SGBagProto.S2C_SoulResolve.newBuilder().// addAllCardIds(cardIds).
				addAllDebrisIds(debrisIds).build().toByteArray());

	}

	/**
	 * 装备碎片分解
	 *
	 * @param playerController
	 * @param data
	 * @param code
	 */
	private void equipResolve(PlayerController playerController, byte[] data, int code) {

		SGBagProto.C2S_EquipResolve request = null;
		try {
			request = SGBagProto.C2S_EquipResolve.parseFrom(data);
		} catch (InvalidProtocolBufferException e) {
			e.printStackTrace();
		}
		if (request == null) {
			playerController.sendWarn(WordFactory.PARAM_ERROR);
			return;
		}

		BagInfo bagInfo = playerController.getPlayer().getExtInfo(BagInfo.class);
		Map<String, GoodsData> cacheMap = new HashMap<>();
		List<Integer> propIds = request.getPropIdsList();
		PropDB prop;
		for (Integer id : propIds) {
			prop = bagInfo.getPropById(id);
			if (prop != null && prop.getConfig().type == ConstantFactory.PROP_TYPE_EQUIP_SYN_EXP) {
				// 将配置数量装换为实际数量
				GoodsData[] result = new GoodsData[prop.getConfig().soulData.length];
				for (int i = 0; i < prop.getConfig().soulData.length; i++) {
					result[i] = new GoodsData(prop.getConfig().soulData[i].type, prop.getConfig().soulData[i].id,
							prop.getConfig().soulData[i].value * prop.count);
				}
				// bagInfo.addGoods(result, null);
				GoodsData goodsData;
				for (GoodsData g : result) {
					goodsData = cacheMap.get(g.type + "_" + g.id);
					if (goodsData == null) {
						goodsData = new GoodsData(g.type, g.id, g.value);
						cacheMap.put(g.type + "_" + g.id, goodsData);
					} else {
						goodsData.value += g.value;
					}
				}
				bagInfo.addProp(id, -prop.count);
			} else {
				LogUtils.error("装备碎片分解错误，背包物品找不到或者物品不是装备碎片：" + id);
				playerController.sendWarn(WordFactory.PARAM_ERROR);
				return;
			}

		}
		GoodsData[] result = new GoodsData[cacheMap.size()];
		int i = 0;
		for (GoodsData goodsData : cacheMap.values()) {
			result[i++] = goodsData;
		}

		bagInfo.addGoods(result);

		playerController.sendMsg(code,
				SGBagProto.S2C_EquipResolve.newBuilder().addAllPropIds(propIds).build().toByteArray());
	}

	/**
	 * 获取分解数据
	 *
	 * @param type
	 * @param quality
	 * @return
	 */
	public GoodsData[] getResolveData(int type, int quality) {
		List<ResolveConfig> resolveConfig = DataFactory.getInstance().getDataList(DataFactory.RESOLVE_DATA_KEY);
		for (ResolveConfig data : resolveConfig) {
			if (type == data.type && quality == data.quality) {
				return data.goods;
			}
		}
		return null;
	}

}
